import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import sun.misc.BASE64Encoder;

public class threadTest implements Runnable {
	private static int count = 0;
	private String video;
	private double lenght;
	private test parent;
	private String userAgent = "Mozilla/5.0(iPad; U; CPU OS 4_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8F191 Safari/6533.18.5";
	private String build_id;
	private String[] proxyArray = new String[2];
	private Map<String, String> cookie = null;
	String referrer = "";
	
	threadTest(String video, double lenght, String build_id,
			String[] proxyArray, test parent) {
		this.video = video;
		this.lenght = lenght;
		this.parent = parent;
		this.build_id = build_id;
		this.proxyArray = proxyArray;
	}

	public void run() {
		try {
			System.out.println("=================");
			count++;
			System.out.println(count);
			System.out.println("=================");
			this.cookie = null;
			sendRequest(
					"http://m.youtube.com/watch?desktop_uri=%2Fwatch%3Fv%3D"
							+ this.video + "&v=" + this.video + "&gl=NL", null);

			GetParams gp = new GetParams(this.video, this.lenght, this.build_id);
			Map data = gp.generateData(false, true, this.referrer);
			sendRequest("http://s.youtube.com/s", data);
			data = gp.generateData(true, this.referrer);
			sendRequest("http://m.youtube.com/user_watch", data);

			this.parent.n += 1;
			do {
				gp.updateStEt();
				Thread.sleep(Integer.valueOf(
						Long.toString(Math.round((gp.et - gp.st) * 1000.0D)))
						.intValue());

				data = gp.generateData(false, this.referrer);
				sendRequest("http://s.youtube.com/s", data);
			} while (gp.et < gp.len);

			gp.updateStEt();
			gp.et -= gp.et - gp.len;
			gp.et -= new Random().nextDouble() / 1000.0D;
			gp.et = (Double.valueOf(
					Integer.valueOf(Long.toString(Math.round(gp.et * 1000.0D)))
							.intValue()).doubleValue() / 1000.0D);
			int time = Integer.valueOf(
					Long.toString(Math.round((gp.et - gp.st) * 1000.0D)))
					.intValue();
			if (time > 0) {
				Thread.sleep(time);
			}

			data = gp.generateData(false, this.referrer);
			sendRequest("http://s.youtube.com/s", data);
			this.parent.n += 1;
			System.out.println(this.parent.n);
		} catch (NumberFormatException e) {
			System.out.println(e.getMessage());
		} catch (InterruptedException e) {
			System.out.println(e.getMessage());
		} catch (NullPointerException e) {
			System.out.println(e.getMessage());
		} catch (IOException e) {
			if (!e.getMessage().equals("Connection refused: connect")) {
				System.out.println(e.getMessage());
			}
		}

		this.parent.fireNewThread();
	}

	private void sendRequest(String url, Map<String, String> data)
			throws IOException, NullPointerException {
		if (data != null) {
			url = url + "?";
			for (int i = 0; i < data.size(); i++) {
				if (i != 0) {
					url = url + "&";
				}
				url = url + data.keySet().toArray()[i] + "="
						+ data.values().toArray()[i];
			}
		}

		HttpURLConnection uc = null;
		if (this.proxyArray != null) {
			Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
					this.proxyArray[0], Integer.valueOf(this.proxyArray[1])
							.intValue()));
			uc = (HttpURLConnection) new URL(url).openConnection(proxy);
			if (this.proxyArray.length > 3) {
				BASE64Encoder enc = new BASE64Encoder();
				String userpassword = this.proxyArray[2] + ":"
						+ this.proxyArray[3];
				String encodedAuthorization = enc.encode(userpassword
						.getBytes());
				uc.setRequestProperty("Authorization", "Basic "
						+ encodedAuthorization);
			}
		} else {
			uc = (HttpURLConnection) new URL(url).openConnection();
		}

		uc.setReadTimeout(5000);
		uc.setConnectTimeout(5000);

		uc.setRequestProperty("User-Agent", this.userAgent);
		uc.setRequestProperty("Referer", "http://m.youtube.com/");
		uc.setRequestProperty("Accept", "*/*");
		uc.setRequestProperty("Accept-Language", "en-us");
		uc.setRequestProperty("Accept-Encoding", "gzip, deflate");
		uc.setRequestProperty("Connection", "keep-alive");

		if (this.cookie != null) {
			String cookieString = "";
			for (int i = 0; i < this.cookie.size(); i++) {
				if (i != 0) {
					cookieString = cookieString + "; ";
				}
				cookieString = cookieString + this.cookie.keySet().toArray()[i]
						+ "=" + this.cookie.values().toArray()[i];
			}
			uc.addRequestProperty("Cookie", cookieString);
		}

		uc.connect();

		if (data == null) {
			List cookies = (List) uc.getHeaderFields().get("Set-Cookie");
			this.cookie = new HashMap();
			for (int i = 0; i < cookies.size(); i++) {
				String[] cookieArray = ((String) cookies.get(i)).split(";")[0]
						.split("=");
				while (cookieArray.length > 2) {
					int tmp573_572 = 1;
					String[] tmp573_570 = cookieArray;
					tmp573_570[tmp573_572] = (tmp573_570[tmp573_572] + "=" + cookieArray[2]);
					cookieArray = removeElement(cookieArray, cookieArray[2]);
				}
				if (cookieArray.length > 1)
					this.cookie.put(cookieArray[0], cookieArray[1]);
				else {
					this.cookie.put(cookieArray[0], "");
				}
			}

		}

		uc.disconnect();
		uc.getInputStream().close();
	}

	public static String[] removeElement(String[] input, String deleteMe) {
		String[] result = new String[input.length - 1];

		int n = 0;
		String[] arrayOfString1 = input;
		int j = input.length;
		for (int i = 0; i < j; i++) {
			String item = arrayOfString1[i];
			if (!deleteMe.equals(item)) {
				result[n] = item;
				n++;
			}
		}

		return result;
	}
}